package com.atguigu.juc.locks;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平锁和非公平锁
 * @author yfstart
 * @create 2022-06-28 19:05
 */
public class SaleTicketDemo {
  public static void main(String[] args) {

    Ticket ticket = new Ticket();
    new Thread(()->{for (int i = 0; i < 55; i++) {ticket.sale();}},"a").start();
    new Thread(()->{for (int i = 0; i < 55; i++) {ticket.sale();}},"b").start();
    new Thread(()->{for (int i = 0; i < 55; i++) {ticket.sale();}},"c").start();
  }
}

/** 资源类：模拟3个售票员卖完50张票 */
class Ticket {
  ReentrantLock lock = new ReentrantLock(true);
  private int number = 50;

  public void sale() {
    lock.lock();
    try {
      if (number > 0) {
        System.out.println(
            Thread.currentThread().getName() + " 卖出第：\t" + (number--) + "\t还剩下：" + number);
      }
    } finally {
      lock.unlock();
    }
  }
}
